#include "./../inc/db_link_list.h"

NODE * create_link_list(void)
{
   NODE * head_node = (NODE *)malloc (sizeof(NODE));
   if(NULL == head_node)
   {
        printf("POINTER IS NULL ERROR.\r\n");
        return NULL;
   }
   head_node->data = NULL;
   head_node->next = NULL;
   head_node->pre = NULL;
   return head_node;
}

int add_db_link_list(NODE* db_link_list,int add_mode,LINK_LIST_DATA_TYPE* data)
{
   if(db_link_list == NULL)
   {
      printf("POINTER IS NULL ERROR.\r\n");
      return POINTER_IS_NULL_ERROR;
   }
   NODE* new_node = (NODE*) malloc (sizeof(NODE));
   new_node->data = NULL;
   new_node->next = NULL;
   new_node->pre = NULL;
   switch(add_mode)
   {
      case HEAD_INSERT:
         new_node->next = db_link_list->next;
         if(new_node->next != NULL)
         {
            new_node->next->pre = new_node;
         }
         new_node->pre = db_link_list;
         new_node->data = data;
         break;
      case TRAIL_INSERT:
         {
            NODE * slide =  db_link_list;

            while(slide->next != NULL)
            {
               slide = slide->next;
            }
            slide->next = new_node;
            new_node->pre = slide;
            new_node->data = data;
         }
         break;
      default:
         {  
            NODE * slide =  db_link_list;
            if(add_mode < -2)
            {
               return ADD_DB_LINK_LIST_POSITION_FAULT;
            }
            int pos = 0;
            while (slide != NULL && pos < add_mode)
            {
               slide = slide->next;
               pos ++;
            }
            if(slide == NULL)
            {
               return ADD_DB_LINK_LIST_POSITION_FAULT;
            }
            new_node->next = slide->next;
            slide->next = new_node;
            new_node->pre = slide;
            new_node->data = data;
         }
         break;
   }
   return ADD_DB_LINK_LIST_DATA_OK;
}


int show_db_link_list(NODE* db_link_list)
{
   if(NULL == db_link_list)
   {
      printf("POINTER IS NULL ERROR.\r\n");
      return POINTER_IS_NULL_ERROR;
   }
   NODE* slide =  db_link_list->next;
   while(slide != NULL)
   {  

      printf("is_encryption = %d\r\n",slide->data->is_encryption);
      printf("data_format = %s\r\n",slide->data->data_format);
      printf("supplement = %s\r\n",slide->data->supplement);
      printf("content = %s\r\n",slide->data->content);
      slide = slide->next;
   }
   return SHOW_DB_LINK_LIST_OK;
}

int destroy_db_link_list(NODE** db_link_list)
{
   if(*db_link_list == NULL)
   {
      return POINTER_IS_NULL_ERROR;
   }
   //先释放节点数据
   NODE * slide = *db_link_list;
   while ((*db_link_list)->next != NULL)
   {  
      slide = slide->next;
      (*db_link_list)->next = slide;
      free(slide);
      slide = NULL;
   }
   free(*db_link_list);
   return DESTROY_DB_LINK_LIST_OK;
}